package com.dlc.felear.xiaoensale.utils;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.itdlc.android.library.utils.FileUtil;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

import okhttp3.Call;

public class MenuPicUtil implements Handler.Callback {
    private static final String TAG = "MenuPicUtil";
    private String picPath = Environment.getExternalStorageDirectory() + "/zkyc/pic/";
    private static final int WHAT1 = 3322;
    private static MenuPicUtil instance;
    private Context context;
    private Handler handler;
    private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(500);
    private HashMap<String, Long> cachePath = new HashMap<>();
    private HashMap<String, String> cacheNamePath = new HashMap<>();

    private MenuPicUtil(Context context) {
        this.context = context;
        initdata();
        looper();
//        Log.e(TAG,"data:"+ JsonHelper.toJson(picInfoDao.queryForAll()));
    }

    private void initdata() {
        File list = new File(picPath);
        File[] tempDatas = list.listFiles();
        if (tempDatas != null) {
            for (File file : tempDatas) {
                cachePath.put(file.getName(), file.length());
            }
        }
    }

    public List<String> getPicsName() {
        return new ArrayList<>(cachePath.keySet());
    }

    private void looper() {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String name;
                            while ((name = queue.take()) != null) {
                                Log.e(TAG, "任务队列下载:" + FileUtil.getFileNameNoEx(name));
                                if (!cachePath.containsKey(name)) {
                                    downMenuPic(name);
                                    Thread.sleep(500);
                                } else {
                                    Log.e(TAG, "已经下载:" + name);
                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                }
        ).start();
    }


    public static MenuPicUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (MenuPicUtil.class) {
                if (instance == null) {
                    instance = new MenuPicUtil(context);
                }
            }
        }
        return instance;
    }


    private void downMenuPic(final String name) {
        final String url = HttpApi.PIC_URL + name;
        Log.e(TAG, "开始下载:" + name);
        OkHttpManager.HttpGet(url, new FileCallBack(Constant.PIC_PATH, name) {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "下载失败 fileName=" + name + " --" + e.getMessage());
            }

            @Override
            public void onResponse(File response, int id) {
                Log.e(TAG, "下载完成 file=" + response.getName());
                if (response != null) {
                    recordPicInfo(response, url);
                }
            }
        });
    }

    private void recordPicInfo(File response, String url) {
        String id = FileUtil.getFileNameNoEx(response.getName());
        cachePath.put(response.getName(), response.length());
    }


    public String getLoaclpicPath(String name, String tempName) {
        Log.e(TAG,"getLoaclpicPath name="+name+" tempName="+tempName);
        if (TextUtils.isEmpty(name)) {
            String temp = nameChangePic(tempName);
            Log.e(TAG,"getLoaclpicPath1 pic="+temp);
            return temp;
        }
        String tempPath = "";
        if (cachePath.containsKey(name)) {
            tempPath = picPath + name;
        }
        if (TextUtils.isEmpty(tempPath)) {
            tempPath = HttpApi.PIC_URL + name;
        }
        Log.e(TAG, "getLoaclpicPath2 pic="+tempPath);
        return tempPath;
    }

    private String nameChangePic(String name) {
        if (cacheNamePath.containsKey(name)) {
            return HttpApi.PIC_URL + cacheNamePath.get(name);
        }
        return "";
    }


    private void addDownLoadPicTask(String name) {
        Log.e(TAG, "添加下载任务1:" + name);
        if (!TextUtils.isEmpty(name)) {
            queue.offer(name);
        }
    }

    private void saveCacheNamePath(String name, String pic ){
        if(TextUtils.isEmpty(pic)){
            return;
        }
        cacheNamePath.put(name, pic);
    }

    public void addDownLoadPicTask(String name, String pic, long picFileLength) {
        Log.e(TAG, "添加下载任务2:" + pic);
        if (!TextUtils.isEmpty(pic)) {
            saveCacheNamePath(name,pic);
            Log.e(TAG, "图片大小判断:localSize=" + getPicFileLength(pic) + " 理论图片大小:" + picFileLength);
            if (!cachePath.containsKey(pic)) {
                queue.offer(pic);
            } else if (cachePath.containsKey(pic) && getPicFileLength(pic) != picFileLength && picFileLength > 0) {
                FileUtil.deleteFile(picPath + pic);
                queue.offer(pic);
            }
        }
    }

    private long getPicFileLength(String name) {
        if (cachePath.containsKey(name)) {
            return cachePath.get(name);
        }
        return -1;
    }

    public void addDownLoadPicTask(String name, boolean delete) {
        if (delete) {
            if (handler == null) {
                handler = new Handler(this);
            }
            FileUtil.deleteFile(Constant.PIC_PATH + name);
            cachePath.remove(name);
            Message message = new Message();
            message.obj = name;
            message.what = WHAT1;
            handler.sendMessageDelayed(message, 100);
        } else {
            addDownLoadPicTask(name);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == WHAT1) {
            String name = (String) msg.obj;
            addDownLoadPicTask(name);
        }
        return false;
    }
}
